#include "../key/threadpool.h"


CThreadPool::CThreadPool()
{
 
}
CThreadPool::~CThreadPool()
{
    OnStop();
}
 
CThreadPool& CThreadPool::GetInstance()
{
    static CThreadPool instance;
    return instance;
}
 
void CThreadPool::SetMaxThreadNum(const int _iCount)
{
    m_usThreadNum = _iCount;
}
 
void CThreadPool::OnStart()
{
    m_bIsRunning = true;
    
    for (int iIndex = 0; iIndex < m_usThreadNum; ++iIndex)
    {
        m_vctThreads.emplace_back(std::thread(&CThreadPool::DoWork, this));
    }
}
 
void CThreadPool::OnStop()
{
    {
        std::unique_lock<std::mutex> ulock(m_mtx);
        m_bIsRunning = false;
        m_cv.notify_all();
    }
    for (auto& td : m_vctThreads)
    {
        if (td.joinable())
        {
            td.join();
        }
    }
}
 
void CThreadPool::AppendTask(const Task& _task)
{
    std::unique_lock<std::mutex> ulock(m_mtx);
    m_queTasks.push(_task);
    m_cv.notify_one();
}
 
void CThreadPool::DoWork()
{
    while(m_bIsRunning)
    {
        Task task;
        {
            std::unique_lock<std::mutex> ulock(m_mtx);
            if (!m_queTasks.empty())
            {
                task = m_queTasks.front();
                m_queTasks.pop();
            }
            else if (m_queTasks.empty() && m_bIsRunning)
            {
                m_cv.wait(ulock);
            }
        }
 
        if (task)
        {
            std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now();
            task();
            std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();
 
            std::cout << (std::chrono::time_point_cast<std::chrono::microseconds>(end) - 
                  std::chrono::time_point_cast<std::chrono::microseconds>(start)).count() /1000000.00<< std::endl; 
        }
        
    }
}